<template>
  <div class="bar-chart">
    <div
      ref="chart"
      :style="{
        height: elementHeight + 'px',
        width: screenWidth + 'px'
      }"
    ></div>

    <!-- v-show 无法显示的问题解决：width:375px -->
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

// chart这个变量要保持跟ref='chart'一致
const chart = ref(null)
const chartDom = ref(null)
const props = defineProps(['dataX', 'dataY'])
const elementHeight = ref(260)
const screenWidth = ref(window.innerWidth - 50)
// console.log(screenWidth.value, 'screenWidth')

const init = () => {
  const barChart = echarts.init(chart.value)

  const option = {
    title: {
      subtext: '分数'
    },

    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: props.dataX,
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          show: false //隐藏x轴线
        },
        axisTick: {
          show: false //隐藏x轴刻度
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '分数',
        type: 'bar',
        barWidth: '8px',
        data: props.dataY,
        itemStyle: {
          normal: {
            barBorderRadius: [40], // 圆柱弧度
            color: params => {
              /**
               * 0-59
               * 60-79
               * 80-100
               */
              if (params.data <= 59) {
                return '#FF762C'
              } else if (params.data >= 60 && params.data <= 79) {
                return '#4994F5'
              } else {
                return '#00D8AF'
              }
            }
          }
        }
      }
    ]
  }
  option && barChart.setOption(option)

  // echarts 自适应，如果dom元素是自适应高宽，会随之改变echarts大小
  window.addEventListener('resize', () => {
    barChart.resize()
  })
}

onMounted(() => {
  // 解决tab切换不显示echart问题
  nextTick(() => {
    init()
  })
})

watch(
  () => props.dataY,
  val => {
    if (val) {
      if (chart.value) {
        init()
      }
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="less" scoped>
.bar-chart {
  width: 100%;
  background-color: #fff;
  border-radius: 20px;
  padding: 16px;
  box-sizing: border-box;
}
</style>
